package org.beetl.sql.springboot.conf;


import com.zaxxer.hikari.HikariDataSource;
import org.beetl.sql.core.ExecuteContext;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.extend.ParaExtend;
import org.beetl.sql.ext.DBInitHelper;
import org.beetl.sql.springboot.Db;
import org.beetl.sql.starter.SQLManagerCustomize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DatasourceConfig {
	@Autowired
	ApplicationContext ctx;

	@Bean(name = "ds")
	public DataSource datasource(Environment env) {
		HikariDataSource ds = new HikariDataSource();
		ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
		ds.setUsername(env.getProperty("spring.datasource.username"));
		ds.setPassword(env.getProperty("spring.datasource.password"));
		ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		ds.setMaximumPoolSize(2);
		return ds;
	}

	@Bean
	public SQLManagerCustomize mySQLManagerCustomize() {
		return new SQLManagerCustomize() {
			@Override
			public void customize(String sqlMangerName, SQLManager manager) {
				DBInitHelper.executeSqlScript(manager, "db/schema.sql");
				manager.refresh();
				manager.getSqlManagerExtend().setParaExtend(new ParaExtend(){
					public Map morePara(ExecuteContext ctx){
						Map map = new HashMap();
						map.put("tenantId", Db.localValue.get());
						return map;
					}
				});

			}
		};

	}
}
